package microcredit.db;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BackupFile {

	private static final String SEP = "_";
	private static final String FILE_PREFIX = "mbackup";
	private static final String EXT = ".zip";
	
	private static final DateFormat fileFormat = new SimpleDateFormat("yyyy-MM-dd"+SEP+"HH-mm-ss");
	
	private File file;
	private Date time;
	
	private BackupFile() {
	}
	
	public File getFile() {
		return file;
	}
	public Date getTime() {
		return time;
	}
	
	public static boolean isValidBackupFile(File file) {
		if (file == null) {
			return false;
		} else if (!file.exists()) {
			return false;
		} else if (file.isDirectory()) {
			return false;
		}
		return parseFile(file) != null;
	}
	
	public static BackupFile createNew(File folder) {
		Date time = new Date();
		File file = new File(folder, FILE_PREFIX + SEP 
				+ fileFormat.format(time) + EXT);
		BackupFile bfile = new BackupFile();
		bfile.file = file;
		bfile.time = time;
		return bfile;
	}
	
	public static BackupFile create(File f) {
		return parseFile(f);
	}
	
	private static BackupFile parseFile(File f) {
		String[] chunks = f.getName().split(SEP);
		if (chunks.length < 3) {
			return null;
		}
		if (!chunks[0].equals(FILE_PREFIX)) {
			return null;
		}
		String dateTimeString = chunks[1]+ SEP + chunks[2];
		Date dateTime;
		try {
			dateTime = fileFormat.parse(dateTimeString);
		} catch (ParseException e) {
			return null;
		}
		
		BackupFile file = new BackupFile();
		file.file = f;
		file.time = dateTime;
		
		return file;
	}
	
	
}
